#include "customdomaincreatedlg.h"
#include "ui_customdomaincreatedlg.h"
#include "ctcascader.h"
//#include <QFile>
//#include <QMessageBox>
#include "tdomain.h"
#include "global.h"

CustomDomainCreateDlg::CustomDomainCreateDlg(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CustomDomainCreateDlg)
{
    ui->setupUi(this);
    m_tDomain = static_cast<TDomain *>(QWidget::parentWidget());
    //this->m_db = m_tDomain->m_dbMySql->m_mysqlConn;
    //m_db = g_mysqlPool.getConnection();
    m_db = m_tDomain->m_dbMySql->m_mysqlConn;
    QMap<QString, QVector<QString>> cascadedItems {
                                                  {"指南", {"设计原则", "导航"}},
                                                  {"组件", {"按钮", "表单", "弹窗"}},
                                                  {"资源", {"图标", "字体", "模板"}}
    };
    getDnDictFromDb();
    //qDebug()<<m_cascadedItems;
    ui->wd_one->setCascadedItemsNew(m_cascadedItemsNew);
    connect(ui->wd_one, &CTCascader::dcascadedSelected, this, [&](QString sts) {slotSelectDictionary(1,sts);});
}

CustomDomainCreateDlg::~CustomDomainCreateDlg()
{
    //g_mysqlPool.releaseConnection(m_db);
    delete ui;
}

void CustomDomainCreateDlg::on_pb_Close_clicked()
{
    this->close();
}

void CustomDomainCreateDlg::slotSelectDictionary(int idx,QString selectStr)
{
    //qDebug()<<selectStr<<idx;
    m_selectedDictStr = selectStr;
//
}

void CustomDomainCreateDlg::getDnDictFromDb()
{

    QSqlQuery query(m_db);
    query.prepare("SELECT id, name, path FROM custom_tree_control where treetype = ? ORDER BY path");
    query.addBindValue(m_treeType);
    m_cascadedItemsNew.clear();
    //QMap<QString, QStringList*> Items;

    if (query.exec())
    {
        QHash<int, QStringList*> nodeMap; // 用于保存每个节点ID对应的QStandardItem对象

        while (query.next()) {
            int nodeId = query.value(0).toInt();
            QString nodeName = query.value(1).toString();
            QString nodePath = query.value(2).toString();
            //qDebug()<<nodeName<<nodePath;
            QStringList pathParts = nodePath.split('/');
            QStringList *parentItem = nullptr;

            // 获取当前节点的父节点
            for (int i = 1; i < pathParts.size() - 1; ++i)
            {
                int parentId = pathParts[i].toInt();

                if (nodeMap.contains(parentId))
                {
                    parentItem = nodeMap[parentId];

                }
                else
                {
                    qDebug() << "Invalid parent ID detected, skipping node: " << nodeId;
                    continue;
                }
            }

            // 创建并添加新的节点

            if (parentItem)
            {
                //qDebug()<<nodeName;
                parentItem->append(nodeName);
                m_selectedDictStr = nodeName;
            }
            else
            { // 如果是根节点，将其添加至模型的根项
                QStringList *listItem = new QStringList;
                m_cascadedItemsNew[nodeName]=listItem;
                nodeMap[nodeId] = listItem; // 将新节点添加到映射表中
            }

        }
    } else {
        qDebug() << "Failed to execute query: " << query.lastError().text();
    }
}

void CustomDomainCreateDlg::getUsedDnSuffix()
{
    m_prefixOne.clear();
    m_prefixTwo.clear();
    m_usedDnSuffix.clear();
    QString ctStr;
    ctStr = ui->plainText_one->toPlainText();
    if(ctStr.length())
    {
        QStringList preone = ctStr.split('\n');
        m_prefixOne.append(preone);
    }

    ctStr = ui->plainText_two->toPlainText();
    if(ctStr.length())
    {
        QStringList pretwo = ctStr.split('\n');
        m_prefixTwo.append(pretwo);
    }

    if(ui->checkBox_com->isChecked())
        m_usedDnSuffix.append(ui->checkBox_com->text());
    if(ui->checkBox_net->isChecked())
        m_usedDnSuffix.append(ui->checkBox_net->text());
    if(ui->checkBox_org->isChecked())
        m_usedDnSuffix.append(ui->checkBox_org->text());
    if(ui->checkBox_cc->isChecked())
        m_usedDnSuffix.append(ui->checkBox_cc->text());
    if(ui->checkBox_biz->isChecked())
        m_usedDnSuffix.append(ui->checkBox_biz->text());
    if(ui->checkBox_info->isChecked())
        m_usedDnSuffix.append(ui->checkBox_info->text());
    if(ui->checkBox_name->isChecked())
        m_usedDnSuffix.append(ui->checkBox_name->text());
    if(ui->checkBox_top->isChecked())
        m_usedDnSuffix.append(ui->checkBox_top->text());
    if(ui->checkBox_wang->isChecked())
        m_usedDnSuffix.append(ui->checkBox_wang->text());
    if(ui->checkBox_cn->isChecked())
        m_usedDnSuffix.append(ui->checkBox_cn->text());
    if(ui->checkBox_comcn->isChecked())
        m_usedDnSuffix.append(ui->checkBox_comcn->text());
    if(ui->checkBox_netcn->isChecked())
        m_usedDnSuffix.append(ui->checkBox_netcn->text());
    if(ui->checkBox_orgcn->isChecked())
        m_usedDnSuffix.append(ui->checkBox_orgcn->text());
    if(ui->checkBox_china->isChecked())
        m_usedDnSuffix.append(ui->checkBox_china->text());

    ctStr = ui->plainText_custom->toPlainText();
    if(ctStr.length())
    {
        if(!ctStr.contains('.'))
        {
            QMessageBox::information(this,"提示","自定义域名缺少'.'符号!");
            return;
        }
        QStringList pathParts = ctStr.split(',');
        m_usedDnSuffix.append(pathParts);
    }
//    qDebug()<<m_prefixOne;
//    qDebug()<<m_prefixTwo;
//    qDebug()<<m_usedDnSuffix;
}

void CustomDomainCreateDlg::on_btn_import_one_clicked()
{
    if(m_selectedDictStr.length()==0)
    {
        QMessageBox::information(this,"提示","请选择字典!");
        return;
    }
    ui->plainText_one->clear();
    QSqlQuery query(m_db);
    query.prepare(" select a.dicttext  from domain_dictionary a,custom_tree_control b where b.name = ? and b.id = a.dicttypeid");
    query.addBindValue(m_selectedDictStr);

    if (query.exec() && query.next())
    {
        ui->plainText_one->setPlainText(query.value(0).toString());
    }
    else
    {
        qDebug() << "Failed to retrieve path for parent ID: " << m_selectedDictStr;
    }
}


void CustomDomainCreateDlg::on_btn_clear_one_clicked()
{
    ui->plainText_one->clear();
}


void CustomDomainCreateDlg::on_btn_import_two_clicked()
{
    if(m_selectedDictStr.length()==0)
    {
        QMessageBox::information(this,"提示","请选择字典!");
        return;
    }
    ui->plainText_two->clear();
    QSqlQuery query(m_db);
    query.prepare(" select a.dicttext  from domain_dictionary a,custom_tree_control b where b.name = ? and b.id = a.dicttypeid");
    query.addBindValue(m_selectedDictStr);

    if (query.exec() && query.next())
    {
        ui->plainText_two->setPlainText(query.value(0).toString());
    }
    else
    {
        qDebug() << "Failed to retrieve path for parent ID: " << m_selectedDictStr;
    }
}


void CustomDomainCreateDlg::on_btn_clear_two_clicked()
{
    ui->plainText_two->clear();
}


void CustomDomainCreateDlg::on_pb_Create_clicked()
{
    if(m_selectedDictStr.length()==0)
    {
        QMessageBox::information(this,"提示","请选择字典!");
        return;
    }
    getUsedDnSuffix();
    if(m_usedDnSuffix.length()==0)
    {
        QMessageBox::information(this,"提示","请选择域名后缀!");
        return;
    }
    QStringList producta ;
    if(m_prefixOne.size()==0&&m_prefixTwo.size()==0)
    {
        QMessageBox::information(this,"提示","请选择域名前缀!");
        return;
    }
    else if(m_prefixOne.size()&&m_prefixTwo.size())
    {
        producta = cartesianProduct(m_prefixOne, m_prefixTwo);
        //qDebug() << producta.size()<<producta;
    }
    else
    {
        if(m_prefixOne.size())
            producta = m_prefixOne;
        else
            producta = m_prefixTwo;
    }

    m_transferData = cartesianProduct(producta, m_usedDnSuffix);
    //qDebug() << productb.size()<<productb;
    ui->dn_total->setText("总数:"+QString::number(m_transferData.size()));
    ui->plainText_dn->clear();
    ui->plainText_dn->setPlainText(m_transferData.join("\n"));

}

QStringList CustomDomainCreateDlg::cartesianProduct(const QStringList &a, const QStringList &b) {
    QStringList result;
    for (const QString &elementA : a) {
        for (const QString &elementB : b) {

            result << elementA + elementB;
            //qDebug()<<elementA<<elementB<<result;
        }
    }
    return result;
}

void CustomDomainCreateDlg::on_btn_clear_clicked()
{
    m_transferData.clear();
    ui->plainText_dn->clear();
    ui->dn_total->setText("总数:");
}

void CustomDomainCreateDlg::on_pb_joinList_clicked()
{
    QString msg = "当前导入记录数："+QString::number(m_transferData.size())+",确认导入？";
    QMessageBox::StandardButton result= QMessageBox::question(this,"提示",msg);
    if(result==QMessageBox::No)
    {
        return;
    }
    if(m_transferData.length())

        emit dataTransfer(m_transferData);
    this->close();
}



